<template>
    <div class="all">
        <div class="Upload">
            <img src="@/assets/文件上传.png" style="width:25px;position: absolute;top:22px;" />
            <h3 style="position: relative;left:30px;">文件分析上传</h3>
            <div class="UploadT">
                <el-upload  class="upload-demo" drag style="width:800px;" action="undefined" :on-change="handleChange"
                    :auto-upload="false" multiple>
                    <el-icon class="el-icon--upload" style="height:63px;"><upload-filled /></el-icon>
                    <div class="el-upload__text">
                        Drop file here or <em>click to upload</em>
                    </div>
                    <template #tip>
                        <div class="el-upload__tip" style="color:white;">
                            拖拽或点击上传文件
                        </div>
                    </template>
                </el-upload>
                <div class="upload-file">
                    <h5 style="position:absolute;top:10px;left:30px;color:white">文件上传列表</h5>
                    <el-upload v-model:file-list="fileList" class="upload-demo" action="undefined"
                        :on-change="handleChange" :auto-upload="false"
                        style="overflow-y: auto;width: 460px;height:245px;margin-left: 20px;margin-top:10px;">
                        <template #file="{ file }" >
                            <div class="el-upload-list__item">
                                <el-icon>
                                    <Document style="position: relative;top:3px;" />
                                </el-icon>
                                <span class="el-upload-list__item-name"
                                    style="width:380px;overflow: hidden; text-overflow:ellipsis;white-space: nowrap" @click="ToDetectionResult(file)">{{file.name }}</span>
                                <span v-if="IsShow(file.name)" class="el-upload-list__item-action"
                                    style="position:absolute;right:40px;">
                                    <el-icon>
                                        <Check style="color: aliceblue;"/>
                                    </el-icon>
                                </span>
                                <span @click="DeleteFile(file.uid)"
                                    style="position:absolute;right:10px;">
                                    <el-icon ><DeleteFilled /></el-icon>
                                </span>
                            </div>
                        </template>
                    </el-upload>
                </div>
            </div>
        </div>
        <div
            style="background-color: rgba(0, 0, 0, 0.3); width:95%;height:60px;position:relative;top:30px; left:35px;box-shadow: 0 0px 35px rgba(0, 20, 230, 0.6);border-radius: 10px;">
            <!-- background-color: rgba(0, 0, 0, 0.5); -->
            <el-button class="detection" type="primary" plain @click="StartDetection()">立即检测</el-button>
            <el-progress v-if="show === 1" class="percent" :percentage="percentage" :text-inside="true"
                :stroke-width="20" striped striped-flow :duration="25" /><!-- 正常 -->
            <el-progress v-if="show === 2" class="percent" :percentage="percentage" :stroke-width="20" status="success"
                striped striped-flow :duration="25" /><!-- 成功 -->
            <el-progress v-if="show === 3" class="percent" :percentage="percentage" :stroke-width="20"
                status="exception" striped striped-flow :duration="0" /><!-- 停止或出错 -->
            <el-button class="detectionEnd" type="primary" plain @click="EndDetection()">结束检测</el-button>
        </div>
        <h1 style="color:white;position:absolute;top:450px;left:550px;">本地apk文件分析上传</h1>
        <div style="height:200px;width:100%;position: absolute;top:1450px;"></div> 
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, watch,computed } from 'vue'
const show = ref(1)
const canChange =ref(true)
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import {useStore} from 'vuex'
const store = useStore();
import type { UploadProps, UploadUserFile } from 'element-plus'
const formData = ref<any>({  
  // 其他表单字段...  
  files: [] as UploadUserFile[]  
}); 
const fileList = ref<UploadUserFile[]>([
])
const AfterFileList = ref([
    
])
const percentage = ref(0)
 
watch(() => {  
  const fileListLength = fileList.value.length;  
  const afterFileListLength = AfterFileList.value.length;  
  
  // 防止除以0的错误  
  if (fileListLength === 0) {  
    percentage.value = 0; // 或者设置为 '0%' 或任何适当的默认值  
    return;  
  }  
  
  // 计算百分比并更新 percentage 的值  
  const calculatedPercentage = Math.round((afterFileListLength / fileListLength) * 100);  
  animateProgress(percentage.value,calculatedPercentage); // 直接更新为数值  
  if(percentage.value===100){
    show.value=2;
  }
});  
//非线性增长效果
function animateProgress(currentPercentage,targetPercentage) {
  // 设置一个增加的步长，可以根据需要调整
  const step = 0.01; // 每次增加1个百分点

  // 判断当前百分比是否小于目标百分比
  if (currentPercentage < targetPercentage) {
    percentage.value += step; 
    currentPercentage+=step;// 增加百分比值
    console.log('1111')

    // 使用 requestAnimationFrame 来持续执行动画
    requestAnimationFrame(animateProgress);
  } else {
    percentage.value = targetPercentage; // 当达到目标百分比时，直接设置为目标值
  }
}
watch(fileList, (newFileList, oldFileList) => {
    console.log('fileList has changed:');
    console.log('Old file list:', oldFileList);
    console.log('New file list:', newFileList);

   
}, {
    // 设置为深度监听，因为我们要监听数组内部的变化  
    deep: true,
    // 如果你想在组件初始化时立即执行一次回调，可以设置 immediate 为 true  
    immediate: false // 默认是 false  
});
const handleChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
    if(canChange.value===true){
    if (!fileList.value.includes(uploadFile)) {
        fileList.value.push(uploadFile);
    }
}else{
    ElMessage({
        message: '正在检测，请不要随意修改文件',
        type: 'warning',
        })
}
}
function DeleteFile(uid:number){
    if(canChange.value===true){
    const updatedFiles = fileList.value.filter(f => f.uid !== uid);  
    fileList.value = updatedFiles;  
    }else{
    ElMessage({
        message: '正在检测，请不要随意修改文件',
        type: 'warning',
        })
}
}
function IsShow(name: String) {
    return AfterFileList.value.some(Fname => Fname === name);
}
function ToDetectionResult(file){
    if(IsShow(file.name)){
    let url1 = `/Main/DetectionResult/${file.name}`;  //对接口的时候要改param1
    // 使用window.open打开新标签页  
    window.open(url1, '_blank');  
    }else{
        ElMessage({
        message: '该文件还未检测完成，请等待检测完成',
        type: 'warning',
        })
    }
}
let intervalId = null; //计时器
import axios from 'axios'
const fileNames = computed(() => { 
  return fileList.value.map(file => file.name);  
}); 
import { serverAddress } from '@/config'
function StartDetection(){
    canChange.value=false;
    show.value=1;
    const formData1=new FormData();
    formData.value.files = fileList.value; 
    console.log('FORMDATA',formData.value.files);
    formData.value.files.forEach((file,index)=>{
        console.log(file);
        formData1.append('aPKFiles', file.raw);
    console.log('键', Array.from(formData1.keys()));
    console.log('值', Array.from(formData1.values()));
    })
    // formData1.append('aPKFiles',formData.value.files);
    formData1.append('userId',store.state.UserInformation.Id)
    console.log('表单',JSON.stringify(formData1))
    
    console.log('名称',fileNames.value);
    axios({
        url:'https://apifoxmock.com/m2/4743995-0-default/190250093',
        //  url:`${serverAddress}/apkUpload/APkUploadByFiles`,
        method:'POST',
        data:formData1,
        headers: {  
        'Content-Type': 'application/x-www-form-urlencoded'  
    }  
    }).then((Response)=>{
        console.log('response',Response.data)
        if(Response.data.code===1){

            // intervalId = setInterval(fetchData, 5000); 
        }else{
            ElMessage({
        message: '上传错误,请重新上传',
        type: 'warning',
        })
        }

    }).catch((error)=>{
        ElMessage({
        message: '上传错误,请重新上传',
        type: 'warning',
        })
    })
    setTimeout(()=>{
        animateProgress(percentage.value,50)
        AfterFileList.value.push('WK.apk'); 
    },240000)
    setTimeout(()=>{
        animateProgress(percentage.value,100)
        AfterFileList.value.push('dtxw.apk'); 
    },480000)
} 
//询问检测完成的apk
async function fetchData() {  
    console.log('fileNames',fileNames.value)
    axios({
        url:'https://apifoxmock.com/m2/4743995-0-default/190432572',
        // url:`${serverAddress}/apkUpload/getFilesReadyNumber?apkNames=${fileNames}`,
        method:'GET',
        // data:{
        //     apkNames:fileNames.value,
        // }
    }).then((response)=>{
        console.log('里请求回应',response.data.data); 
        if(response.data.data!==null){
        response.data.data.forEach(element => {
        console.log(element,'After',AfterFileList.value)
        if(!AfterFileList.value.includes(element)){
            AfterFileList.value.push(element); 
            console.log('加入',element,'After为',AfterFileList.value);
        }
    });
    if (percentage.value===100) {  
        console.log('清除计时器')
      clearInterval(intervalId);  
    }  
}
    }).catch((error)=>{
        console.log('Failed to fetch data:', error);
    })
}  
function EndDetection(){
    canChange.value=true;
    show.value=3;
    clearInterval(intervalId); 
    console.log('清除计时器') 
}
</script>
<style scoped>
h3 {
    color: white;
    position: relative;
    top: -10px;
    margin-bottom: 10px;
}

.percent {
    width: 80%;
    height: 1px;
    position: absolute;
    top: 40px;
    left: 135px;
}

.percent {
    color: white !important;
}

.detectionContext {
    width: 95%;
    height: 88%;
    position: absolute;
    top: 405px;
    left: 35px;
    background-color: rgba(0, 0, 0, 0.3);
    box-shadow: 0 0px 25px rgba(0, 20, 230, 0.6);
    border-radius: 10px;
    padding: 10px;
}

.detectionStatistics {
    width: 95%;
    height: 93%;
    position: absolute;
    top: 1010px;
    left: 35px;
    background-color: rgba(0, 0, 0, 0.3);
    box-shadow: 0 0px 25px rgba(0, 20, 230, 0.6);
    border-radius: 10px;
    padding: 10px;
}

.detection {
    position: absolute;
    top: 15px;
    left: 20px;
}

.detectionEnd {
    position: absolute;
    top: 15px;
    right: 20px;
}

.all {
    position: absolute;
    top: 130px;
    width: 100% !important;
    height: 670px !important;
    overflow-y: auto;
}

.Upload {
    width: 95%;
    height: 45%;
    background-color: rgba(0, 0, 0, 0.3);
    position: relative;
    left: 35px;
    top: 20px;
    border-radius: 10px;
    padding-left: 30px;
    padding-top: 30px;
    box-shadow: 0 0px 25px rgba(0, 20, 230, 0.6);
    overflow: hidden;
}

.upload-file {
    background-color: rgba(0, 0, 0, 0.417);
    height: 260px;
    border-radius: 5px;
    width: 500px;
    position: absolute;
    top: 20px;
    left: 850px;
}

.Upload::-webkit-scrollbar,
.upload-demo::-webkit-scrollbar {
    width: 5px;
    height: 0px;
}

.UploadT {
    overflow-y: auto;
    height: 220px;
}

.all::-webkit-scrollbar {
    width: 0 !important;
    height: 0 !important;
}

.upload-file::-webkit-scrollbar {
    width: 7 !important;
    height: 0 !important;
}

.UploadT::-webkit-scrollbar {
    width: 8px;
    height: 4px;
}

.UploadT::-webkit-scrollbar-track {
    background: #f1f1f1;
    /* 滚动条的背景颜色 */
    border-radius: 10px;
    /* 可选：滚动条的圆角 */
}

.UploadT::-webkit-scrollbar-thumb {
    background: #cacaca;
    /* 滑块（thumb）的颜色 */
    border-radius: 10px;
    /* 滑块（thumb）的圆角 */
    box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
    /* 可选：滑块（thumb）的阴影效果 */
}

.UploadT::-webkit-scrollbar-thumb:hover {
    background: #9d9d9d;
    /* 滑块（thumb）在鼠标悬停时的颜色 */
}
</style>